package com.wwf.config;

import com.wwf.pojo.Configuration;
import com.wwf.pojo.MappedStatement;
import com.wwf.sqlsession.SqlType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperConfigBuilder {
    private Configuration configuration;
    public XmlMapperConfigBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream in) throws DocumentException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        this.parseSqlNode(rootElement,SqlType.select.name(),namespace);
        this.parseSqlNode(rootElement,SqlType.update.name(),namespace);
        this.parseSqlNode(rootElement,SqlType.insert.name(),namespace);
        this.parseSqlNode(rootElement,SqlType.delete.name(),namespace);
    }
    protected void parseSqlNode(Element rootElement, String sqlType,String namespace){
        List<Element> list = rootElement.selectNodes("//"+sqlType+"");
        for (Element element: list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlTex = element.getTextTrim();
            String key = namespace+"."+id;
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSqlTex(sqlTex);
            mappedStatement.setSqlType(sqlType);
            configuration.getMappedSatements().put(key,mappedStatement);
        }
    }
}
